//
//  MHAppDelegate.m
//  MHO
//
//  Created by papo on 2/15/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHAppDelegate.h"
#import "Lib.h"
#import "MongooseDaemon.h"
#import "HTTPServer.h"

@interface MHAppDelegate()
@property (nonatomic, strong) MongooseDaemon*   mongooseDaemon;
@property (nonatomic, strong) HTTPServer*       httpServer;
@end

@implementation MHAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [Lib setUserLogin:NO];
    [Lib checkUpdate];
    
    // Mongoose
//    self.mongooseDaemon = [[MongooseDaemon alloc] init];
//    [self.mongooseDaemon startMongooseDaemon:@"8080"];
    
    // Http server
    self.httpServer = [[HTTPServer alloc] init];
    
    [self.httpServer setType:@"_http._tcp."];
    
    [self.httpServer setPort:8081];
    
    [self.httpServer setDocumentRoot:[Lib getDocumentPath]];
    
    [self.httpServer setName:@"MHO Server"];
    
//    [self.httpServer setDomain:@"https://localhost/"];
    if ([self.httpServer isRunning]) {
        NSLog(@"stop server");
        [self.httpServer stop];
    }
    
    NSError* error;
    if ([self.httpServer start:&error]) {
        NSLog(@"Start server success at port: %d", [self.httpServer listeningPort]);
        NSLog(@"Domain: %@", [self.httpServer domain]);
        NSLog(@"Name: %@", [self.httpServer name]);
    }
    else {
        NSLog(@"Start server error: %@", [error debugDescription]);
    }
    
    
    // register remote notification
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *mySettings =
        [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
    }
    
//    NSLog(@"notification: %d", [[UIApplication sharedApplication] isRegisteredForRemoteNotifications]);
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[MHRootViewController alloc] initWithNibName:@"MHRootViewController" bundle:nil];
    
    
    self.window.rootViewController = self.viewController;
    
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    // check internet connection
    self.reachability = [Reachability reachabilityForInternetConnection];
    [self.reachability setUnreachableBlock:^(Reachability * reachability) {
        NSLog(@"internet unreachable!");
    }];
    [self.reachability setReachableBlock:^(Reachability * reachability) {
        NSLog(@"internet reachable!");
    }];
    [self.reachability startNotifier];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
//    [self.mongooseDaemon stopMongooseDaemon];
    [self.httpServer stop];
}


#pragma mark - Remote Notification
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Remote Notification failed: %@", [error debugDescription]);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"Remote Notification register with device token: %@", token);
    [ServiceLib sendGetRequest:[NSString stringWithFormat:@"http://mobile.mho.vn/services/NotificationTongBu?DeviceId=%@&IdSystem=1&key=%@", token, kServerKey] useCache:NO];
}


+ (MHAppDelegate*)sharedApp {
    return (MHAppDelegate*)[UIApplication sharedApplication].delegate;
}

@end
